package com.rich.util;

import android.media.AudioSystem;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;

public class MicTsetUtils {

	private static MediaRecorder mRecorder;

	private static MediaPlayer mPlayer;

	public static void start() {
		Log.d("lrs", "start");
		if (mPlayer != null) {
			mPlayer.stop();
		}
		String sDcString = Environment.getExternalStorageState();
		if (!sDcString.equals(Environment.MEDIA_MOUNTED)) {
			Log.d("lrs", "sdcard_tips_failed");
			// mRecord.setText(R.string.sdcard_tips_failed);
			return;
		}
		try {
			AudioSystem.setParameters("SET_MIC_CHOOSE=0");
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
			mRecorder.setAudioChannels(2);
			mRecorder.setAudioEncodingBitRate(128000);
			mRecorder.setAudioSamplingRate(48000);
			String path = Environment.getExternalStorageDirectory() + File.separator + "test.amr";
			File file = new File(path);
			mRecorder.setOutputFile(file.getAbsolutePath());
			if (!file.exists())
				file.createNewFile();
			mRecorder.prepare();
			mRecorder.start();
		} catch (Exception e) {
			mRecorder.reset();
			mRecorder.release();
			mRecorder = null;
		}
	}

	public static void stopAndSave() {
		Log.d("lrs", "stopAndSave");
		try {
			mRecorder.reset();
			mRecorder.release();
			mRecorder = null;
			mPlayer = new MediaPlayer();
			mPlayer.setDataSource("/sdcard/test.amr");
			mPlayer.prepare();
			mPlayer.start();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (RuntimeException e) {
			e.printStackTrace();
		}
	}

	public static void stop() {
		File file = new File(Environment.getExternalStorageDirectory() + File.separator + "test.amr");
		file.delete();
		if (mPlayer != null) {
			mPlayer.stop();
		}
		if (mRecorder != null) {
			mRecorder.reset();
			mRecorder.release();
			mRecorder = null;
		}
	}

}
